package be.ipl.finito.servlets;

import java.io.IOException;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.ipl.finito.domaine.Partie;
import be.ipl.finito.usecases.GestionJoueur;
import be.ipl.finito.usecases.GestionPartie;

@SuppressWarnings("serial")
public class ListerParties extends HttpServlet{

	@EJB
	private GestionPartie gestionPartie;
	@EJB
	private GestionJoueur gestionJoueur;
	
	public ListerParties(){
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if(req.getSession().getAttribute("pseudo")==null){
			resp.sendRedirect("index.html");
			return;
		}
		List<Partie> lesParties = this.gestionPartie.listerParties();
		Map<Integer, Long> timers = new HashMap<Integer, Long>();
		Enumeration<String> idsParties = getServletContext().getAttributeNames();
		while (idsParties.hasMoreElements()) {
			String s = idsParties.nextElement();
			if (s.startsWith("time")) {
				Calendar now = new GregorianCalendar();
				Calendar created = (Calendar) getServletContext().getAttribute(s);
				long rest = (Partie.TEMPS * 1000) + created.getTimeInMillis() - now.getTimeInMillis();
				int id = Integer.parseInt(s.substring(4));
				timers.put(id, rest);
			}
		}
		req.setAttribute("timers", timers);
		req.setAttribute("lesParties", lesParties);
		req.setAttribute("nbParties", lesParties.size());
		getServletContext().getNamedDispatcher("listerParties.jsp").forward(req, resp);
		
	}
}
